
import { ReactNode, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useAuthStore } from '@/stores/auth'
import { Spin } from 'antd'

interface AuthGuardProps {
  children: ReactNode
  roles?: string[]
}

export default function AuthGuard({ children, roles = [] }: AuthGuardProps) {
  const navigate = useNavigate()
  const location = useLocation()
  const { isAuthenticated, user, loading } = useAuthStore()

  useEffect(() => {
    if (loading) return

    if (!isAuthenticated) {
      navigate('/login', {
        state: { from: location },
        replace: true
      })
      return
    }

    if (roles.length > 0 && !roles.includes(user?.role || '')) {
      navigate('/403', { replace: true })
    }
  }, [isAuthenticated, loading, user, roles])

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <Spin size="large" />
      </div>
    )
  }

  return <>{children}</>
}
